package cn.edu.njust.epms.controller;


import cn.edu.njust.epms.common.R;
import cn.edu.njust.epms.common.Resp;
import cn.edu.njust.epms.entity.IORecord;
import cn.edu.njust.epms.entity.User;
import cn.edu.njust.epms.entity.uItem;
import cn.edu.njust.epms.service.ItemService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/item")
public class ItemController {
    @Autowired
    ItemService is;

    /**
     * 提交物资申请
     * @param i
     * @return
     */
    @PutMapping("/apply")
    public Resp<uItem> apply(HttpServletRequest request,@RequestBody uItem i){
        User user = (User)request.getSession().getAttribute("user");
//        if(user == null)
//            return Resp.error("请先登录！");
        i.setuId(user.getuId());
//        System.out.println(i);
        Resp<uItem> apply = is.apply(i);
        return apply;
    }

    /**
     * 获取物资申请记录
     * @param r
     * @return
     */
    @PostMapping("/apply")
    public Resp<PageInfo<uItem>> allApply(HttpServletRequest request, @RequestBody R r){
        User user = (User)request.getSession().getAttribute("user");
        if(user.getuSts()!=2){//非管理员只能查看自己的记录
            r.setuId(user.getuId());
        }
        Integer _pageNo = 1;//默认分页参数
        Integer _size = 5;
        String order="oId";
        if (r.getPageNo() != null) {
            _pageNo = r.getPageNo();
        }
        if (r.getSize() != null) {
            _size = r.getSize();
        }
        if (r.getOrder() != null && r.getOrder().length() > 0) {//没有传入排序，则默认以rId排序
            order=r.getOrder();
        }
        PageHelper.startPage(_pageNo,_size,order);
        Resp<List<uItem>> listResp = is.selectByCondition(r);
        PageInfo<uItem> pageInfo = new PageInfo<>(listResp.getData());
        return Resp.success(pageInfo);
    }

    /**
     * 下载物资申请记录
     * @param request
     * @param response
     */
    @GetMapping("/download")
    public void export(HttpServletRequest request, HttpServletResponse response){
        HSSFWorkbook book = new HSSFWorkbook();
        String FileName = "ItemApply_"+new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+".xls";
        HSSFSheet sheet1 = book.createSheet("sheet1");
        Resp<List<uItem>> arrayListResp = is.selectByCondition(new R());
        List<uItem> data = arrayListResp.getData();
        HSSFRow row0 = sheet1.createRow(0);
        sheet1.setColumnWidth(0,8*256);
        sheet1.setColumnWidth(1,17*256);
        sheet1.setColumnWidth(2,24*256);
        sheet1.setColumnWidth(3,20*256);
        sheet1.setColumnWidth(4,20*256);
        sheet1.setColumnWidth(5,20*256);
        sheet1.setColumnWidth(6,10*256);
        row0.createCell(0).setCellValue("物资申请订单号");
        row0.createCell(1).setCellValue("申请人");
        row0.createCell(2).setCellValue("申请人身份证号");
        row0.createCell(3).setCellValue("申请时间");
        row0.createCell(4).setCellValue("申请物资");
        row0.createCell(5).setCellValue("用户留言");
        row0.createCell(6).setCellValue("状态");
        for (int i = 1; i <= data.size(); i++) {
            uItem record = data.get(i - 1);
            HSSFRow row = sheet1.createRow(i);
            row.createCell(0).setCellValue(record.getoId());
            row.createCell(1).setCellValue(record.getUd().getName());
            row.createCell(2).setCellValue(record.getUd().getPid());
            SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            row.createCell(3).setCellValue(format.format(record.getoTime()));
            row.createCell(4).setCellValue(record.getReq());
            if(record.getuNote() != null)
                row.createCell(5).setCellValue(record.getuNote());
            switch (record.getoState()){
                case 0:
                    row.createCell(6).setCellValue("已提交");
                    break;
                case 1:
                    row.createCell(6).setCellValue("审核通过");
                    break;
                case 2:
                    row.createCell(6).setCellValue("审核不通过");
                    break;
                default:
                    row.createCell(6).setCellValue("未知");
            }
        }
        response.setHeader("Content-Disposition","attachment; filename="+FileName);
        response.setContentType("application/binary;charset=ISO8859_1");
        response.setCharacterEncoding("GB2312");
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            book.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 审核订单
     * @param i
     * @return
     */
    @PutMapping("/audit")
    public Resp<uItem> auditOrder(HttpServletRequest request,@RequestBody uItem i){
        User user = (User)request.getSession().getAttribute("user");

        if(user==null||user.getuSts()!=2){
            return Resp.error("拒绝访问");
        }
        if(i.getoNote()==null||i.getoNote().length()==0){
            i.setoNote(" ");
        }
        Resp<uItem> resp = is.audit(i);
        return resp;
    }

    /**
     * 删除订单
     * 慎用！！！
     * @param id
     * @return
     */
    @DeleteMapping("/audit/{id}")
    public Resp<String> deleteOrder(HttpServletRequest request,@PathVariable("id") Integer id){
        User user = (User)request.getSession().getAttribute("user");
        if(user==null||user.getuSts()!=2){
            return Resp.error("拒绝访问");
        }
        Resp<String> stringResp = is.deleteOrder(id);
        return stringResp;
    }
}
